package drds.global_transaction.api.message_codec.rpc_message;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import lombok.Getter;
import lombok.Setter;

public class RpcMessageFuture
{
	private static final Object NULL = new Object();
	private final CountDownLatch countDownLatch = new CountDownLatch(1);

	@Setter
	@Getter
	private RpcMessage requestMessage;
	@Setter
	@Getter
	private long timeout;
	@Setter
	@Getter
	private long startDateTimeLong = System.currentTimeMillis();
	@Setter
	@Getter
	private volatile Object resultMessage;

	public boolean isTimeout()
	{
		return System.currentTimeMillis() - startDateTimeLong > timeout;
	}

	public Object get(long timeout, TimeUnit timeUnit) throws TimeoutException, InterruptedException
	{
		boolean success = countDownLatch.await(timeout, timeUnit);
		if (!success)
		{
			throw new TimeoutException("cost " + (System.currentTimeMillis() - startDateTimeLong) + " ms");
		}
		if (resultMessage instanceof RuntimeException)
		{
			throw (RuntimeException) resultMessage;
		} else if (resultMessage instanceof Throwable)
		{
			throw new RuntimeException((Throwable) resultMessage);
		}
		return resultMessage;
	}

	public void setResultMessage(Object object)
	{
		this.resultMessage = (object == null ? NULL : object);
		countDownLatch.countDown();
	}
}
